import tensorflow
from tensorflow import keras
from sklearn.preprocessing import StandardScaler
import numpy as np
import os

(train_x, train_y), (test_x, test_y)  = keras.datasets.fashion_mnist.load_data()
valid_x, valid_y = train_x[:5000], train_y[:5000]
train_x, train_y = train_x[5000:], train_y[5000:]

model = keras.Sequential([
    keras.layers.Flatten(),
    keras.layers.Dense(300,activation='relu'),
    keras.layers.Dense(200,activation='relu'),
    keras.layers.Dense(10,activation='softmax')
])

model.build(input_shape=[None,28,28])
model.summary()

model.compile(  
    optimizer = keras.optimizers.SGD(0.001),
    loss = keras.losses.sparse_categorical_crossentropy,  # 标签用的数字：sparse_categorical_crossentrpy
                                                          # 标签用的one-hot: categorical_crossentrpy
    metrics = ['accuracy']
)


 # tensorboard和modelcheckpoint的路径要用os.path.join来添加 不能写直接路径
logdir = os.path.join('callbacks')
if not os.path.exists(logdir):
    os.mkdir(logdir)
model_file = os.path.join(logdir,'model.h5')

callbacks = [
    keras.callbacks.TensorBoard(logdir),
    keras.callbacks.ModelCheckpoint(model_file,save_best_only=True),
    keras.callbacks.EarlyStopping(monitor='val_acc',min_delta=20,patience=0)  # 连续出现0次(即出现一次) 
]                                                                                  # 增长小于20则停止训练

model.fit(train_x,train_y,epochs=3,validation_data=(valid_x,valid_y),callbacks=callbacks)

